package lab4;

import java.awt.Button;
import java.awt.Frame;
import java.awt.Panel;
import java.awt.TextArea;
import java.awt.Toolkit;
import java.io.IOException;
import java.net.ServerSocket;
import java.util.ArrayList;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class Server {

	static int end = 0;
	public static ServerSocket socket;
	public static ArrayList<ConnectedClient> clients = new ArrayList<>();

	private static void close() {
		end = 1;
		try {
			Server.socket.close();
		} catch (IOException e) {
			System.out.println("can't close soket");
		}
	}

	public static void main(String[] args) throws IOException {

		socket = new ServerSocket(1999);
		final Frame f = new Frame("Сервер чата");
		f.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				f.setVisible(false);
				f.dispose();
				close();
			}

		});
		TextArea text = new TextArea(25, 60);
		text.setEditable(false);
		Button b = new Button("Отключить");
		Panel p = new Panel();
		p.add(text);
		p.add(b);
		f.setSize(500, 500);
		f.setLocation(
				Toolkit.getDefaultToolkit().getScreenSize().width / 2 - 250,
				Toolkit.getDefaultToolkit().getScreenSize().height / 2 - 250);
		f.add(p);
		b.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent arg0) {
				f.setVisible(false);
				f.dispose();
				close();
			}

		});
		f.setVisible(true);

		while (end == 0) {
			ConnectedClient client = null;
			try {
				client = new ConnectedClient(socket.accept(), text);
				synchronized (Server.clients) {
					clients.add(client);
				}
				client.start();

			} catch (IOException e) {
				System.out.println("soket was closed");
			}
		}

	}

}
